package com.cslg.ac.demo.interceptor;

import com.cslg.ac.demo.constant.ResponseCode;
import com.cslg.ac.demo.entity.user.User;
import com.cslg.ac.demo.util.communicate.ResponseUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
public class SessionAuthInteceptor implements HandlerInterceptor {

    private static final String[] REQUIRE_NOT_AUTH_URLS = new String[]{
            "/user/login", "/user/register", "/user/authPhone","/user/authSucceed/{email}/{id}",
            "/user/authSuccess", "/user/getTeam",
            "/person/getInfo",
            "/team/getTable", "/team/getInfo",
            "/email/isAuth",  "/idCard/isAuth",
            "/donate/getInfo",
            "/host/getInfo",
            "/album/download", "/video/download", "/photo/download", "/text/download",
            "/image/download",
            "/like/get", "/like/follow",
            "/pet/getPetsByMaster", "/pet/getInfo",
            "/pet/sortByTime", "/host/sort",
            "/post/getByPost", "/post/getByUser", "/post/get",
            "/sign/signToday", "/sign/getSignDay",
            "/host/sortByAddress", "/host/sortByCredit",
            "/search/petSortByFive"
    };

    private boolean containsNotAuthUrl(String url){
        for(String get : REQUIRE_NOT_AUTH_URLS){
            if(url.equals(get)){
                return true;
            }
        }
        return false;
    }


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestUrl = httpServletRequest.getRequestURI();
        if(containsNotAuthUrl(requestUrl)){
            return true;
        }
        User user = (User) httpServletRequest.getSession().getAttribute("user");
        if(user == null){
            ResponseUtil.responseCode(httpServletResponse, ResponseCode.NOT_LOGON);
            // 如果是return false的话，它不会调用下一个拦截器/处理器, 即流程马上结束
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
